import { lazy, Suspense, useEffect } from 'react'
import { Navigate } from 'react-router-dom'

const Home = lazy(() => import('@/pages/Home/home'))
const Examination = lazy(() => import('@/pages/examination/examination'))
const Login = lazy(() => import('@/pages/login/login'))
const Register = lazy(() => import('@/pages/register/register'))
const Edit = lazy(() => import('@/pages/edit/edit'))
const EditBaseInfo = lazy(() => import('@/pages/edit/components/base-info'))
const EditAvatar = lazy(() => import('@/pages/edit/components/avatar'))
const AfterExam = lazy(() => import('@/pages/examination/afterexam'))

// const withLoadingComponent = (component: JSX.Element, title?: string) => {
//   const pageTitle = title || 'GG考试系统'
//   console.log(title)
//   useEffect(() => {
//     document.title = pageTitle
//   }, [pageTitle])
//   return <Suspense fallback="加载中">{component}</Suspense>
// }
// useLoadingComponent(Examination, 'GG考试')

const WithLoadingComponent: React.FC<{ component: JSX.Element; title?: string }> = ({ component, title = 'GG考试系统' }) => {
  useEffect(() => {
    document.title = title
  }, [title])

  return <Suspense fallback="加载中">{component}</Suspense>
}

const routes = [
  {
    path: '/',
    meta: { isPrivate: false },
    element: <Navigate to="/home" />
  },
  {
    path: '/home',
    meta: { isPrivate: false },
    element: <WithLoadingComponent component={<Home />} title="GG答题" />
  },
  {
    path: '/exam',
    meta: { isPrivate: true },
    element: <WithLoadingComponent component={<Examination />} />
  },
  {
    path: '/login',
    meta: { isPrivate: false },
    element: <WithLoadingComponent component={<Login />} title="登陆" />
  },
  {
    path: '/register',
    meta: { isPrivate: false },
    element: <WithLoadingComponent component={<Register />} title="注册" />
  },
  {
    path: '/my',
    meta: { isPrivate: true },
    element: <WithLoadingComponent component={<Register />} title="个人中心" />
  },
  {
    path: '/edit',
    meta: { isPrivate: true },
    element: <WithLoadingComponent component={<Edit />} title="编辑资料" />,
    children: [
      {
        path: 'base',
        meta: { isPrivate: true },
        element: <WithLoadingComponent component={<EditBaseInfo />} title="编辑资料" />
      },
      {
        path: 'avatar',
        meta: { isPrivate: true },
        element: <WithLoadingComponent component={<EditAvatar />} title="编辑资料" />
      }
    ]
  },
  {
    path: '/afterexam',
    meta: { isPrivate: true },
    element: <WithLoadingComponent component={<AfterExam />} />
  }
]

export default routes
